package com.cleaningcloud.cld.service.impl;

import com.cleaningcloud.cld.api.domain.CldRecruitPlan;
import com.cleaningcloud.cld.api.domain.CldStaff;
import com.cleaningcloud.cld.api.domain.Vo.CldStaffDto;
import com.cleaningcloud.cld.domain.CldRecruitPlanDetails;
import com.cleaningcloud.cld.domain.vo.CldStaffVo;
import com.cleaningcloud.cld.mapper.CldRecruitPlanDetailsMapper;
import com.cleaningcloud.cld.mapper.CldRecruitPlanMapper;
import com.cleaningcloud.cld.mapper.CldStaffMapper;
import com.cleaningcloud.cld.service.ICldStaffService;
import com.cleaningcloud.cld.service.PublicCommonService;
import com.cleaningcloud.common.core.constant.UserConstants;
import com.cleaningcloud.common.core.exception.ServiceException;
import com.cleaningcloud.common.core.utils.DateUtils;
import com.cleaningcloud.common.core.utils.StringUtils;
import com.cleaningcloud.common.security.utils.SecurityUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 人员花名册Service业务层处理
 *
 * @author cleaningcloud
 * @date 2024-10-12
 */
@Service
public class CldStaffServiceImpl implements ICldStaffService {
    @Autowired
    private CldStaffMapper cldStaffMapper;

    @Autowired
    private PublicCommonService publicCommonService;

    @Autowired
    private CldRecruitPlanMapper cldRecruitPlanMapper;

    @Autowired
    private CldRecruitPlanDetailsMapper cldRecruitPlanDetailsMapper;


    /**
     * 查询人员花名册
     *
     * @param staffId 人员花名册主键
     * @return 人员花名册
     */
    @Override
    public CldStaffVo selectCldStaffByStaffId(Long staffId) {
        return cldStaffMapper.selectCldStaffByStaffId(staffId);
    }

    /**
     * 查询人员花名册列表
     *
     * @param cldStaff 人员花名册
     * @return 人员花名册
     */
    @Override
    public List<CldStaffVo> selectCldStaffList(CldStaffDto cldStaff) {
        return cldStaffMapper.selectCldStaffList(cldStaff);
    }

    @Override
    public String importStaff(List<CldStaff> staffList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(staffList) || staffList.size() == 0) {
            throw new ServiceException("导入员工数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CldStaff staff : staffList) {
            try {
                // 验证是否存在这个用户
                CldStaff cldStaff = cldStaffMapper.selectStaffByStaffPhone(staff.getStaffPhone());
                if (StringUtils.isNull(cldStaff)) {
                    staff.setStaffPassword(SecurityUtils.encryptPassword("123456"));
                    staff.setCreateBy(operName);
                    staff.setStaffNo(String.valueOf(cldStaffMapper.selectStaffCount() + 1));
                    staff.setStaffStatus(1);
                    staff.setFlag(0L);
                    cldStaffMapper.insertCldStaff(staff);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + staff.getStaffName() + " 导入成功");
                } else if (isUpdateSupport) {
                    cldStaff.setStaffId(cldStaff.getStaffId());
                    cldStaffMapper.updateCldStaff(staff);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + staff.getStaffName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工 " + staff.getStaffName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + staff.getStaffName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public Map<String, Object> selectCldStaffAnalyze() {
        return cldStaffMapper.selectCldStaffAnalyze();
    }

    /**
     * 新增人员花名册
     *
     * @param cldStaff 人员花名册
     * @return 结果
     */
    @Override
    public int insertCldStaff(CldStaff cldStaff) {
        cldStaff.setCreateTime(DateUtils.getNowDate());
        cldStaff.setStaffStatus(1);
        cldStaff.setFlag(0L);
        if (StringUtils.isNotEmpty(cldStaff.getStaffPassword())) {
            String password = cldStaff.getStaffPassword();
            cldStaff.setStaffPassword(SecurityUtils.encryptPassword(password));
        }
        cldStaff.setStaffNo(String.valueOf(cldStaffMapper.selectStaffCount() + 1));
        return cldStaffMapper.insertCldStaff(cldStaff);
    }

    @Override
    public int reinstatementStaff(Long staffId) {
        return cldStaffMapper.clearResignInfo(staffId);
    }

    /**
     * 修改人员花名册
     *
     * @param cldStaff 人员花名册
     * @return 结果
     */
    @Override
    public int updateCldStaff(CldStaff cldStaff) {
        return cldStaffMapper.updateCldStaff(cldStaff);
    }

    @Override
    @Transactional
    public int resignCldStaff(CldStaff cldStaff) {
        cldStaff.setResignApprovalStatus(3L);
        cldStaff.setResignAppTime(DateUtils.getNowDate());
        cldStaff.setResignApprovalId(SecurityUtils.getUserId());
        cldStaff.setResignApprovalTime(DateUtils.getNowDate());
        cldStaffMapper.updateCldStaff(cldStaff);
        // 如离职日期小于等于当天 则立马离职
        if (cldStaff.getResignTime().compareTo(new Date()) <= 0) {
            CldStaffVo cldStaffVo = cldStaffMapper.selectCldStaffByStaffId(cldStaff.getStaffId());
            publicCommonService.staffOptions(cldStaffVo.getStaffId(), 1, cldStaffVo.getProjectId(), null);
        }
        return 1;
    }

    /**
     * 批量删除人员花名册
     *
     * @param staffIds 需要删除的人员花名册主键
     * @return 结果
     */
    @Override
    public int deleteCldStaffByStaffIds(Long[] staffIds) {
        return cldStaffMapper.deleteCldStaffByStaffIds(staffIds);
    }

    /**
     * 删除人员花名册信息
     *
     * @param staffId 人员花名册主键
     * @return 结果
     */
    @Override
    @Transactional
    @GlobalTransactional(rollbackFor = Exception.class)
    public int deleteCldStaffByStaffId(Long staffId) {
        publicCommonService.staffOptions(staffId, 4, null, null);
        return cldStaffMapper.deleteCldStaffByStaffId(staffId);
    }

    /**
     * 员工离职
     */
    @Override
    public void staffResignation() {
        // 查询离职时间为当日或之前的数据
        CldStaffDto query = new CldStaffDto();
        query.setIsResignation(1L);
        List<CldStaffVo> cldStaffVos = cldStaffMapper.selectCldStaffList(query);
        for (CldStaffVo cldStaffVo : cldStaffVos) {
            publicCommonService.staffOptions(cldStaffVo.getStaffId(), 1, cldStaffVo.getProjectId(), null);
        }
    }

    @Override
    public CldStaff selectStaffByStaffPhone(String staffPhone) {
        return cldStaffMapper.selectStaffByStaffPhone(staffPhone);
    }

    @Override
    @Transactional
    public boolean registerStaff(CldStaff cldStaff) {
        cldStaff.setRegisterTime(DateUtils.getNowDate());
        cldStaff.setFlag(0L);
        cldStaff.setCreateTime(DateUtils.getNowDate());
        cldStaff.setStaffStatus(0);
        cldStaff.setResumePrintStatus(0L);
        cldStaff.setStaffNo(String.valueOf(cldStaffMapper.selectStaffCount() + 1));
        int i = cldStaffMapper.insertCldStaff(cldStaff);
        if (StringUtils.isNotEmpty(cldStaff.getReferrerPhone())) {
            CldRecruitPlan cldRecruitPlan = cldRecruitPlanMapper.selectCldRecruitPlanByRecruitPhone(cldStaff.getReferrerPhone());
            if (cldRecruitPlan == null) {
                throw new ServiceException("招聘计划查询失败！");
            }
            cldStaff.setRecommenStaffId(cldRecruitPlan.getRecruitLeadingId());
            // 插入招聘员工记录
            CldRecruitPlanDetails cldRecruitPlanDetails = new CldRecruitPlanDetails();
            cldRecruitPlanDetails.setStaffId(cldStaff.getStaffId());
            cldRecruitPlanDetails.setRecruitPlanId(cldRecruitPlan.getRecruitPlanId());
            cldRecruitPlanDetails.setRecruitTime(DateUtils.getNowDate());
            cldRecruitPlanDetailsMapper.insertCldRecruitPlanDetails(cldRecruitPlanDetails);
        }
        return i > 0;
    }

    @Override
    public boolean checkUserPhoneUnique(CldStaff cldStaff) {
        Long staffId = StringUtils.isNull(cldStaff.getStaffId()) ? -1L : cldStaff.getStaffId();
        CldStaff info = cldStaffMapper.checkPhoneUnique(cldStaff.getStaffPhone());
        if (StringUtils.isNotNull(info) && info.getStaffId().longValue() != staffId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkUserIdCardUnique(CldStaff cldStaff) {
        Long staffId = StringUtils.isNull(cldStaff.getStaffId()) ? -1L : cldStaff.getStaffId();
        CldStaff info = cldStaffMapper.checkPhoneUnique(cldStaff.getStaffIdcard());
        if (StringUtils.isNotNull(info) && info.getStaffId().longValue() != staffId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


}
